package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.api.AudioApi;
import com.tanhua.dubbo.enums.IdType;
import com.tanhua.dubbo.pojo.Audio;
import com.tanhua.dubbo.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@DubboService(version = "1.0.0")
@Slf4j
public class AudioApiImpl implements AudioApi {

    @Autowired
    private IdService idService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String uploadAudio(Audio audio) {
        try {
            if (!ObjectUtil.isAllNotEmpty(audio.getAudioUrl(), audio.getUserId())) {
                return null;
            }
            audio.setId(ObjectId.get());
            audio.setAid(idService.createId(IdType.AUDIO));
            audio.setCreated(System.currentTimeMillis());
            this.mongoTemplate.save(audio);
            return audio.getId().toHexString();
        } catch (Exception e) {
            log.error("上传音频文件失败");
        }

        return null;
    }

    /*@Override
    public Audio queryAudioById(Long userId) {
        String idKey = "TANHUA_ID_" + IdType.AUDIO.toString();
        Integer maxAid = Integer.valueOf(redisTemplate.opsForValue().get(idKey));
        int audioAid = RandomUtil.randomInt(0, maxAid) + 1;
        Query query = Query.query(Criteria.where("aid").is(audioAid));
        Audio audio = mongoTemplate.findOne(query, Audio.class);

        if (ObjectUtil.isNotEmpty(audio)) {
            // 查询一次，可查询持续减一
            String redisKey = "REMAINING_TIMES";
            String hashCountKey = "COUNT_" + userId.toString();
            redisTemplate.opsForHash().increment(redisKey, hashCountKey, -1);
            return audio;
        }
        return null;
    }*/

    @Scheduled
    @Override
    public List<Audio> queryAudioById(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        List<Audio> audioList = this.mongoTemplate.find(query, Audio.class);

        if (CollUtil.isNotEmpty(audioList)) {
            return audioList;
        }
        return null;
    }

    @Override
    public Integer getRemainingTimes(Long userId) {
        //查询用户今天剩余次数
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();
        Integer count = 10;
        String redisKey = "REMAINING_TIMES";
        String hashCountKey = "COUNT_" + userId.toString();
        String hashTimeKey = "TIME_" + userId.toString();
        //上次查询时间
        Long lastQuery = Convert.toLong(redisTemplate.opsForHash().get(redisKey, hashTimeKey));
        //第一次使用该功能,新建键值
        if (ObjectUtil.isEmpty(lastQuery)) {
            lastQuery = System.currentTimeMillis();
            redisTemplate.opsForHash().put(redisKey, hashTimeKey, Convert.toStr(lastQuery));
            redisTemplate.opsForHash().put(redisKey, hashCountKey, "10");
        }
        //上次查询时间小于今天的最小时间则判定为新的一天,重置次数
        if (lastQuery < minDate) {
            redisTemplate.opsForHash().put(redisKey, hashCountKey, "10");
            lastQuery = System.currentTimeMillis();
            redisTemplate.opsForHash().put(redisKey, hashTimeKey, Convert.toStr(lastQuery));
            return count;
        }
        //在今天的时间范围内
        if (minDate < lastQuery && lastQuery < maxDate) {
            count = Convert.toInt(redisTemplate.opsForHash().get(redisKey, hashCountKey));
            redisTemplate.opsForHash().put(redisKey, hashTimeKey, Convert.toStr(System.currentTimeMillis()));
            if (count <= 0) {
                return 0;
            }
        }
        return count;
    }
}
